package 剑指offer;

public class 剑指Offer22链表中倒数第k个节点 {
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode slow = head;
        ListNode fast = head;
        int count = 0;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            count ++;
        }
        if(fast != null && fast.next == null) count = count * 2 + 1;
        if(fast == null) count = count * 2;
        int index = count - k;//整数第几个
        if(index < count / 2){
            fast = head;
            int i = 0;
            while(index != i){
                fast = fast.next;
                i++;
            }
            return fast;
        }else if(index == count / 2){
            return slow;
        }else{
            int i = count / 2;
            while(index != i){
                slow = slow.next;
                i++;
            }
            return slow;
        }
    }
}
